package com.app.controller;

import com.alibaba.fastjson.JSONArray;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.PersonService;
import com.app.service.TestsRecordService;
import com.app.util.CommonHelp;
import com.app.util.ExcelUtils;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.TestsRecordVo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/tests")
public class TestsRecordController {


    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private TestsRecordService testsRecordService;

    /**
     * 获取试验记录列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getTestsRecordList")
    @ResponseBody
    public Result<Object> getTestsRecordList(
            HttpServletRequest request, TestsRecordModel model,Integer sortType) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        TestsRecordVo vo = testsRecordService.getListByModel(model,sortType);
        return Result.success(vo);
    }

    /**
     * 根据ID获取试验记录
     *
     * @param request
     * @return
     */
    @GetMapping("/getTestsRecord")
    @ResponseBody
    public Result<Object> getTestsRecord(
            HttpServletRequest request, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        TestsRecordModel model = testsRecordService.getModelById(id);
        return Result.success(model);
    }

    /**
     * 编辑
     *
     * @param request
     * @return
     */
    @PostMapping("/editTestsRecord")
    public Result<Object> editTestsRecord(
            HttpServletRequest request, @RequestBody TestsRecordModel model) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (model.getId() != null && model.getId() > 0) {
            model.setUpTime(CommonHelp.getNowTimestamp());
            testsRecordService.update(model);
        } else {
            model.setCrtTime(CommonHelp.getNowTimestamp());
            testsRecordService.insert(model);
        }
        return Result.success("操作成功");
    }

    /**
     * 删除
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/deleteTestsRecord")
    public Result<Object> deleteTestsRecord(HttpServletRequest request, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }


        try {
            testsRecordService.deleteTestsRecord(id);
        } catch (Exception e) {
            return Result.success(e);
        }
        return Result.success("操作成功");
    }

    /**
     * 批量删除实验记录
     */
    @DeleteMapping("/deleteRecordBatchByIds")
    public Result<Object> deleteBatchById(@RequestParam("ids") String ids, HttpServletRequest request) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        // 执行批量删除操作
        return testsRecordService.deleteBatchByIds(ids);
    }

    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
